import 'dart:async';

import 'package:aero_frisbee/app_route.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

class AFOnboardingPage extends ConsumerStatefulWidget {
  const AFOnboardingPage({super.key});
  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _AFOnboardingPageState();
}

class _AFOnboardingPageState extends ConsumerState<AFOnboardingPage> {
  final PageController _pageController =
      PageController(initialPage: 0, viewportFraction: 1);

  final List<String> images = [
    Assets.images.splashBg01.path,
    Assets.images.splashBg02.path,
    Assets.images.splashBg03.path,
  ];
  Timer? _timer;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Listener(
        onPointerDown: (detail) {
          _cancelTimer;
        },
        onPointerCancel: (detail) {
          _autoToNextPage();
        },
        onPointerUp: (detail) {
          _autoToNextPage();
        },
        child: PageView.builder(
          controller: _pageController,
          itemCount: images.length,
          physics: const ClampingScrollPhysics(),
          itemBuilder: (BuildContext context, int index) {
            return GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                _scrollNextPage();
              },
              child: Image.asset(
                images[index],
                alignment: Alignment.topCenter,
                fit: BoxFit.fitWidth,
              ),
            );
          },
        ),
      ),
    );
  }

  _cancelTimer() {
    _timer?.cancel();
    _timer = null;
  }

  _autoToNextPage() {
    _timer?.cancel();
    _timer = Timer(const Duration(seconds: 2), () {
      _scrollNextPage();
    });
  }

  _scrollNextPage() {
    if (_pageController.page == 2) {
      ///跳转登录
      context.replaceNamed(
        RouteUri.toLaunch,
      );
    } else {
      _pageController.nextPage(
          duration: const Duration(milliseconds: 500), curve: Curves.linear);
    }
    _autoToNextPage();
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _autoToNextPage();
    });
    super.initState();
  }

  @override
  void dispose() {
    _pageController.dispose();
    _timer?.cancel();
    _timer = null;
    super.dispose();
  }

  @override
  void didUpdateWidget(AFOnboardingPage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
